package com.clear.subject.common.context;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 登录上下文对象
 */
public class LoginContextHolder {

    private static final InheritableThreadLocal<Map<String, Object>> THREAD_LOCAL =
            new InheritableThreadLocal<>();

    public static void set(String key, Object val) {
        Map<String, Object> map = getThreadLocalMap();
        // fixme ConcurrentHashMap k-v 都不能为null，测试时为null报错NullPointerException
        map.put(key, val);
    }

    public static Object get(String key) {
        Map<String, Object> map = getThreadLocalMap();
        return map.get(key);
    }

    public static String getLoginId() {
        Map<String, Object> map = getThreadLocalMap();
        return (String) map.get("loginId");
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }


    /**
     * 拿到threadlocal中的map
     *
     * @return
     */
    private static Map<String, Object> getThreadLocalMap() {
        // 拿map
        Map<String, Object> map = THREAD_LOCAL.get();
        // map如果不存在，创建一个
        if (Objects.isNull(map)) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }

        return map;
    }
}
